/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.usefullc.proxy.test.proxy;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.ssl.SslContext;

public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {

    private final Channel inboundChannel;
//    private final SslContext sslContext;

    public HexDumpProxyBackendHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
//        this.sslContext = sslContext;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.read();
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        String mockData = "HTTP/1.1 200 OK\n" +
                "Content-Type: application/x-javascript\n" +
                "Last-Modified: Thu, 20 Apr 2017 04:34:32 GMT\n" +
                "Accept-Ranges: bytes\n" +
                "ETag: \"81d1d688fb9d21:0\"\n" +
                "Vary: Accept-Encoding\n" +
                "Server: IIS\n" +
                "X-Powered-By: WAF/2.0\n" +
                "Date: Sat, 30 Jul 2022 03:07:44 GMT\n" +
                "Content-Length: 3\n\r\n123\r\n";

//        ((ByteBuf) msg).clear();
//        ((ByteBuf) msg).writeBytes(mockData.getBytes());
        inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        HexDumpProxyFrontendHandler.closeOnFlush(inboundChannel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        HexDumpProxyFrontendHandler.closeOnFlush(ctx.channel());
    }
}
